﻿using GZY.Quartz.MUI.Extensions;
using Microsoft.EntityFrameworkCore;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;
using Pomelo.EntityFrameworkCore.MySql.Internal;
using Quartz;
using Quartz.Impl.AdoJobStore;
using TasksManager.Jobs.Test;

namespace TasksManager
{
    public static class ServiceExtension
    {
        public static IServiceCollection AddQuartzService(this IServiceCollection services,IConfiguration configuration)
        {
            services.AddQuartz((q) =>
            {
                q.UseDefaultThreadPool(x => x.MaxConcurrency = 1);

                q.UseMicrosoftDependencyInjectionJobFactory();

                //q.UsePersistentStore((c) =>
                //{
                //    c.UseProperties = true;
                //    c.UseMySql((mysqlOptions) =>
                //    {
                //        mysqlOptions.UseDriverDelegate<MySQLDelegate>();
                //        mysqlOptions.ConnectionString = configuration.GetConnectionString("MysqlCon").ToString() ?? string.Empty;
                //        mysqlOptions.TablePrefix = "Job_";
                //    });
                //    c.UseJsonSerializer();

                //});

                // 手动注册
                //q.AddJobAndTrigger<DefineJobService>(configuration);
            });

            // 当程序关闭时，此设置可确保等待job正常结束
            services.AddQuartzHostedService(x => x.WaitForJobsToComplete = true);

            //services.AddQuartzUI();
            //services.AddQuartzClassJobs();
            return services;
        }


        public static WebApplicationBuilder AddConfiguration(this WebApplicationBuilder  builder)
        {
            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "JsonConfig");
            IConfigurationBuilder configurationBuilder = builder.Configuration
               .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "JsonConfig"));
            string[] nameArrays = Directory.GetFiles(filePath, "*.json");
            if (nameArrays != null && nameArrays.Length > 0)
            {
                foreach (var item in nameArrays)
                {
                    configurationBuilder.AddJsonFile($"{item}", true, true);
                }
            }
            configurationBuilder.Build();
            
            return builder;
        }


        public static void AddJobAndTrigger<T>(
       this IServiceCollectionQuartzConfigurator quartz,
       IConfiguration config)
       where T : IJob
        {
            string jobName =typeof(T).Name;

            var configKey = $"Quartz:{jobName}";
            var cronSchedule = config[configKey];

            // Some minor validation
            if (string.IsNullOrEmpty(cronSchedule))
                throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");

            // register the job as before
            var jobKey = new JobKey(jobName);
            quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));

            //为作业创建一个触发器
            quartz.AddTrigger(opts => opts
                .ForJob(jobKey)
                .WithIdentity(jobName + "-trigger")
                .WithCronSchedule(cronSchedule)); // use the schedule from configuration
        }

    }
}
